package com.gary.heapJUC;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 6辆车，3车位
 * @author peng_rui
 * @date 2022/3/16
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        //信号灯  3个许可证
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    //获取许可证
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "占用车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "离开车位-------");
                }
            }, i+"号车").start();
        }

    }
}
